﻿using System.Diagnostics;

namespace gpt
{
    public class GptStock
    {
        public const string DefaultFlag = "default_model_flag";
        public const string StockPath = "gpts.txt";
        public string FullStockPath = Path.GetFullPath(StockPath);
        public List<GptModel> Models = new List<GptModel>();
        public int DefaultPoint { get; set; } = 0;

        public GptStock()
        {
            if (!File.Exists(StockPath))
            {
                using var fs = File.Create(StockPath);
            }
            LoadModels();
        }

        public void LoadModels()
        {
            Models.Clear();
            var lines = File.ReadAllLines(StockPath);

            for (int i = 0; i < lines.Length; i++)
            {
                var lineSplit = lines[i].Split(" ",StringSplitOptions.RemoveEmptyEntries);
                
                if(lineSplit.Length < 2 || lineSplit.Take(2).Any(t => t == DefaultFlag))
                {
                    ConsoleTools.ErrorOutNoFormat($"在您的配置文件中读取到异常的行:-:可通过[bold yellow]{AICMD.OpenConfig}[/]打开配置文件进行修改");
                    ConsoleTools.ErrorOut($"LineNum({i + 1}):{ lines[i]}");
                    continue;
                }
                GptModel model = new GptModel();
                model.Model = lineSplit[0];
                model.EndPoint = lineSplit[1];

                if (lineSplit.Length >= 3 && lineSplit[2] != DefaultFlag) model.ApiKey = lineSplit[2];
                if (lineSplit.Last() == DefaultFlag) DefaultPoint = i;

                var recount = 0;
                if(Models.Any(m => m.Equals(model)))
                {
                    ConsoleTools.ErrorOutNoFormat($"在您的配置文件中读取到重复的行:-:可通过[bold yellow]{AICMD.OpenConfig}[/]打开配置文件进行修改");
                    ConsoleTools.ErrorOut($"LineNum({Models.FindIndex(m => m.Equals(m)) + recount + 1}):{lines[i]}");
                    ConsoleTools.ErrorOut($"LineNum({i + 1}):{lines[i]}");
                    recount++;
                    continue;
                }

                Models.Add(model);
            }
        }

        public void SaveModels()
        {
            if (Models == default || Models.Count == 0) return;

            var dataArr = Models.Select(m => {
                var lineDate = m.Model + " " + m.EndPoint;

                if(!string.IsNullOrWhiteSpace(m.ApiKey))
                    lineDate += " " + m.ApiKey;

                if (Models[DefaultPoint].Equals(m))
                    lineDate += " " + DefaultFlag;

                return lineDate;
            });

            var data = string.Join(Environment.NewLine, dataArr);
            File.WriteAllText(StockPath,data);
        }

        public void AddModels(GptModel model)
        {
            Models.Add(model);
            SaveModels();
        }

        public void DelModel(int i)
        {
            Models.RemoveAt(i);
            SaveModels();
        }

        public GptModel GetNewModelByConsole()
        {
            ConsoleTools.SystemSay("请输入模型名称");
            string name = Console.ReadLine();

            ConsoleTools.SystemSay("请输入API地址");
            string endPoint = Console.ReadLine();

            ConsoleTools.SystemSay("请输入秘钥");
            string apiKey = Console.ReadLine();

            ConsoleTools.SystemSay("是否默认？（y/s）");
            string isDefault = Console.ReadLine();

            GptModel model = new GptModel() { Model=name,ApiKey=apiKey,EndPoint=endPoint};
            Models.Add(model);

            if (string.Equals(isDefault, "y",StringComparison.OrdinalIgnoreCase))
            {
                DefaultPoint = Models.IndexOf(model);
            }

            SaveModels();

            return model;
        }

        public GptModel GetDefaultModel()
        {
            if (Models == default || Models.Count == 0) return GetNewModelByConsole();
            return Models[DefaultPoint];
        }

        /// <summary>
        /// 使用默认文本编辑器打开gpts.txt
        /// </summary>
        public void OpenGptsTxt()
        {
            try
            {
                if (!File.Exists(FullStockPath))
                {
                    ConsoleTools.ErrorOut($"配置文件不存在：{FullStockPath}");
                    return;
                }

                var process = new ProcessStartInfo
                {
                    FileName = FullStockPath,
                    UseShellExecute = true,
                    Verb = "open" // 明确指定打开动作
                };

                Process.Start(process);
            }
            catch (Exception ex)
            {
                ConsoleTools.ErrorOut($"自动打开失败，错误：{ex.Message}");
                try
                {
                    // 尝试通过记事本打开
                    Process.Start(new ProcessStartInfo("notepad.exe", FullStockPath));
                }
                catch
                {
                    ConsoleTools.ErrorOut($"请手动打开配置文件：{FullStockPath}");
                }
            }
        }
    }

    public class GptModel
    {
        public string Model { get; set; }
        public string EndPoint { get; set; }
        public string ApiKey { get; set; }

        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
            {
                return false;
            }
            GptModel model = (GptModel)obj;
            return this.Model == model.Model && this.EndPoint == model.EndPoint;
        }
    }
}
